#encoding:utf8 
import os , sys
try:
	from py_ex import *
except:
	import logging

TEMPLATE = "\
local newui = function()\n\
	--create the widgets\n\
	local root = d.node()\n\
{widgetlist}\
	--create the animatin-func\n\
\t--todo animationlist\n\
	return root\n\
end\n\
return newui\n\
"


def CCNode(arg):
	return ""
def CCLayer(arg):
	return ""
def CCSprite(arg):
	return "'"+ arg["displayFrame"][1] + "'"  		#arg texture
def CCLayerGradient(arg):
	return "cc.c4b(%s , %s , %s) , cc.c4b(%s , %s ,%s) , cc.p(%s , %s)" % (arg["startColor"][0] ,arg["startColor"][1] , arg["startColor"][2],  \
		arg["startColor"][0] ,arg["startColor"][1] , arg["startColor"][2] , arg["vector"][0] , arg["vector"][1])
def CCLabelBmFont(arg):
	return "'%s', %s, %s" % (arg["string"],arg["fontName"],arg["horizontalAlignment"] or 1),
def CCLabelTTF(arg):
	return "'%s', %s, %s" % (arg["string"],arg["fontName"],arg["horizontalAlignment"] or 1),
def CCControlButton(arg):
	return "'%s' , '%s'," % (arg["backgroundSpriteFrame|1"] , arg["title|1"] , arg["titleTTF|1"] , arg["horizontalAlignment"] or 1)
def CCScale9Sprite(arg):
	return "'%s', %s, %s" % (arg["spriteFrame"][1], 200,200)


WIDGET_MAP = dict(
	CCNode   = CCNode,
	CCSprite = CCSprite,
	CCLayer = CCLayer,
	CCScale9Sprite = CCScale9Sprite,
	CCLayerGradient = CCLayerGradient,
	CCLabelBmFont = CCLabelBmFont,
	CCLabelTTF = CCLabelTTF,
	CCControlButton = CCControlButton,
	)

WIDGET_CTOR = dict(
	CCNode = "d.node(%s)",
	CCSprite = "d.sp(%s)",
	CCLayer = "d.layer(%s)",
	CCScale9Sprite = "d.sp(%s)",
	CCLayerGradient = "d.colorLayer(%s)",
	CCLabelBmFont = "d.labelBMF(%s)",
	CCLabelTTF = "d.label(%s)",
	CCControlButton = "d.btnLabel(%s)"
	)

WIDGET_NAME = dict(
	CCNode = "node_%s",
	CCSprite = "sp_%s",
	CCLayer = "layer_%s",
	CCScale9Sprite = "sp9_%s",
	CCLayerGradient = "layer_gra%s",
	CCLabelBmFont = "label_%s",
	CCLabelTTF = "labelttf_%s",
	CCControlButton = "btn_%s",
	)

PROPER_MAP = dict(
	position = ":pos(%s,%s)",
	anchor = ":anchor(%s,%s)",
	rotation = ":rotate(%s)",

	# ignoreAnchorPointForPosition = False,
	scale = ":scale(%s,%s)",
	# displayFrame = [],
	# blendFunc = [],
	opacity = ":optatic(%s)",
	parent = ":addTo(%s)"
	)


def __crt_animate_func(anidata):
	print (anidata ,"anidata")

ret_widget = ""
ret_anima  = ""
def __chk_widgetdata(ccbdata):

	global ret_widget
	#widgets
	str_widgetctor = ''
	str_widgetpro = ''
	

	nameindex = dict()


	def chkchildren(parent , data , basestr = ''):
		is_children = False
		global ret_widget
		for children in data:
			#base info
			str_widgetbind = ''
			node_classname   = children["baseClass"]
			node_membername  = children["memberVarAssignmentName"]
			node_displayname = children["displayName"]


			node_parent = parent		#default value
			node_properbase = dict(			
				position = [0,0],
				scale = [1,1],
				rotation = 0,
				opacity = 255
				)
			
			for pro in children["properties"]:
				node_properbase[pro["name"]] = pro["value"]


			if WIDGET_MAP.has_key(node_classname):
				is_membernode = False

				#ctor
				if not node_membername == '':
					is_membernode = True
				else:
					if not nameindex.has_key(node_classname):
						nameindex[node_classname] = 0
					else:
						nameindex[node_classname] = nameindex[node_classname] + 1
					node_membername = (WIDGET_NAME[node_classname]%nameindex[node_classname])
				str_widgetctor = "local %s="%node_membername + WIDGET_CTOR[node_classname] % WIDGET_MAP[node_classname](node_properbase)


				#property
				str_widgetpro= (PROPER_MAP["position"]  % (node_properbase["position"][0] , node_properbase["position"][1])) \
							 + (PROPER_MAP["anchor"]  % (node_properbase["anchorPoint"][0] , node_properbase["anchorPoint"][1])) \
							 + (PROPER_MAP["scale"]  % (node_properbase["scale"][0] , node_properbase["scale"][1])) \
							 + (PROPER_MAP["rotation"]  % node_properbase["rotation"]) \
							 + (PROPER_MAP["opacity"]  % node_properbase["opacity"]) \
							 + (PROPER_MAP["parent"] % (node_parent)) + "\n"


				#member bind
				if is_membernode == True:
					str_widgetbind = "\t%s.%s = %s\n"%(node_parent, node_membername, node_membername)



				ret_widget = ret_widget + "\t" + str_widgetctor + str_widgetpro + str_widgetbind

				#anima bind --todo
				if children.has_key("animatedProperties"):
					str_anibind = ""
					ret_widget = ret_widget + str_anibind


			if len(children["children"]) > 0:
				is_children = True
				chkchildren(node_membername , children["children"] , ret_widget)


	chkchildren("root" , ccbdata["nodeGraph"]["children"])
	return ret_widget

def __chk_animationdata(ccbfile):
	
	global ret_anima
	#todo



def ccb2lua(ccbfile ,tarpath):
	ccbdata = reader_ex.readPlistFile(ccbfile)
	logging.info("Reading ccb file [%s]...." % ccbfile)
	# log_ex.printTable(ccbdata)

	str_graph = __chk_widgetdata(ccbdata)
	str_ani   = __chk_animationdata(ccbdata)

	str_lua = TEMPLATE.replace("{widgetlist}" , str_graph)

	luafile = open(tarpath , "w+")
	luafile.write(str_lua)
	luafile.close()
	logging.info("Write ccb-info to [%s]!" % tarpath)
